package cn.com.taiji.pos.controller.Abandoned;

import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.pos.entity.*;
import cn.com.taiji.pos.service.*;
import com.alibaba.fastjson.JSONObject;
import com.github.dreamyoung.mprelation.AutoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

//@RestController
//@RequestMapping("/FixedConsumption")
public class FixedConsumptionController {

    @Value("${SETTLEMENT_TYPE_ID_YuShouKaJi}")
    private String SETTLEMENT_TYPE_ID_YuShouKaJi;
    @Value("${SETTLEMENT_TYPE_ID_YingShouKaJi}")
    private String SETTLEMENT_TYPE_ID_YingShouKaJi;
    @Value("${SETTLEMENT_TYPE_ID_YingShouCanPiao}")
    private String SETTLEMENT_TYPE_ID_YingShouCanPiao;
    @Value("${ACCOUNT_CATEGORY_ID_jici}")
    private String ACCOUNT_CATEGORY_ID_jici;
    @Autowired
    private ICardInfoService cardInfoService;
    @Autowired
    private ICardCustomerTypeService cardCustomerTypeService;
    @Autowired
    private ISystemPosMachineService systemPosMachineService;
    @Autowired
    private IConfigMealTimeService configMealTimeService;
    @Autowired
    private ICardAccountService cardAccountService;
    @Autowired
    private ITradeAccountConsumptionFlowService tradeAccountConsumptionFlowService;
    @Autowired
    private IConfigQuotaConsumptionService configQuotaConsumptionService;
    @Autowired
    private AutoMapper autoMapper;


    /**
     * 定额消费
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "FixedConsumption", method = RequestMethod.POST)
    public String FixedConsumption(Model model, HttpServletRequest request, HttpServletResponse response) {
        boolean flag = false;
        model.addAttribute("result", "fail");
        SystemAclUser user = (SystemAclUser) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        String cardCode = request.getParameter("cardCode");
        String physicalCode = request.getParameter("physicalCode");
        String money = request.getParameter("money");//钱数
        String canci = request.getParameter("canci");//餐次
//        String OriMoney = money;//原始金额
        CardInfo cardInfo = cardInfoService.findByCardCode(cardCode);
        ConfigMealTime configMealTime = configMealTimeService.findByName(canci);
        if (cardInfo == null) {
            model.addAttribute("message", "您的卡片出现问题，可能被停用，请重新联系开卡部门确认");
            return JSONObject.toJSONString(model);
        } else {
            cardCustomerTypeService.getById(autoMapper.mapperEntity(cardInfo).getCustomer().getCustomerTypeId());
            TradeAccountConsumptionFlow tradeAccountConsumptionFlow = new TradeAccountConsumptionFlow();
            SystemPosMachine systemPosMachine = systemPosMachineService.findByPhysicalCode2(physicalCode);
            if (systemPosMachine != null) {
                tradeAccountConsumptionFlow.setRestaurantId(systemPosMachine.getRestaurantId());
                tradeAccountConsumptionFlow.setPosMachineId(systemPosMachine.getId());
            } else {
                tradeAccountConsumptionFlow.setRestaurantId("");
                tradeAccountConsumptionFlow.setPosMachineId("");
            }
            tradeAccountConsumptionFlow.setMealTimeId(configMealTime.getId());
            tradeAccountConsumptionFlow.setOperateType(0);
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd-");
            tradeAccountConsumptionFlow.setFlowNo("XF-" + systemPosMachine.getProjectCode() + "-" + systemPosMachine.getRestaurantCode() + "-" + configMealTime.getCode() + df.format(LocalDate.now()) + UUID.randomUUID().toString().substring(0, 4));
            ConfigQuotaConsumption configQuotaConsumption = configQuotaConsumptionService.query()
                    .eq("POS_MACHINE_ID", systemPosMachine.getId()).orderByDesc("ID").eq("MEAL_TIME_ID", configMealTime.getId()).one();
            if ("1".equals(configQuotaConsumption.getConfigType())) {
                //定额按钱消费
                List<CardAccount> cardAccountList = cardAccountService.findCardAccountList(cardInfo.getCustomerId(), canci);
                //1.顺序消费 对应餐次消费
                if (cardAccountList.size() > 0) {
                    for (CardAccount cardAccount : cardAccountList) {
                        if (cardAccount.getEffectDate() != null && cardAccount.getEffectDate().getYear() != 1) {
                            if (cardAccount.getEffectDate().isBefore(LocalDate.now())) {
                                continue;
                            }
                        }
                        if (cardAccount.getAmount().compareTo(BigDecimal.ZERO) > 0) {
                            //储值账户有钱
                            if (cardAccount.getAmount().doubleValue() > Double.parseDouble(money)) {
                                //储值账户有钱并且够用
                                if ("储值账户".equals(cardAccount.getSddName())) {
                                    tradeAccountConsumptionFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_YuShouKaJi);
                                } else if ("补助账户".equals(cardAccount.getSddName())) {
                                    tradeAccountConsumptionFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_YingShouKaJi);
                                } else if ("餐票账户".equals(cardAccount.getSddName())) {
                                    tradeAccountConsumptionFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_YingShouCanPiao);
                                }
                                tradeAccountConsumptionFlow.setCustomerId(cardInfo.getCustomerId());
                                tradeAccountConsumptionFlow.setAccountId(cardAccount.getId());
                                tradeAccountConsumptionFlow.setCardId(cardInfo.getId());
                                tradeAccountConsumptionFlow.setBeforeAmount(cardAccount.getAmount());//扣前金额
                                tradeAccountConsumptionFlow.setActualAmount(Double.valueOf(money));//实扣金额
                                tradeAccountConsumptionFlow.setAfterAmount(cardAccount.getAmount().subtract(new BigDecimal(money)));//扣后金额
                                tradeAccountConsumptionFlow.setDiscountAmount(0.0);//折扣金额，待确认
                                tradeAccountConsumptionFlow.setBeforeTimes(cardAccount.getTimes());//操作前次数
                                tradeAccountConsumptionFlow.setTimes(0);
                                tradeAccountConsumptionFlow.setAfterTimes(cardAccount.getTimes());//操作后次数
                                tradeAccountConsumptionFlow.setReasonId("定额消费");
                                tradeAccountConsumptionFlow.setIsPay("0");//是否开具发票
                                tradeAccountConsumptionFlow.setCreatorId(user.getId());
                                tradeAccountConsumptionFlow.setCreatorName(user.getName());
                                tradeAccountConsumptionFlow.setCreateTime(LocalDateTime.now());
                                cardAccount.setAmount(tradeAccountConsumptionFlow.getAfterAmount());
                                cardAccountService.updateById(cardAccount);
                                tradeAccountConsumptionFlowService.save(tradeAccountConsumptionFlow);
                                flag = true;
                            } else {
                                model.addAttribute("message", "账户余额不足");
                                return JSONObject.toJSONString(model);
                            }
                        }
                    }
                } else {
                    //2.顺序消费 非餐次
                    cardAccountList = cardAccountService.findCardAccountList(cardInfo.getCustomerId());
                    if (cardAccountList.size() == 0) {
                        model.addAttribute("message", "本次交易失败,没有可用的账户");
                        return JSONObject.toJSONString(model);
                    }
                    for (CardAccount cardAccount : cardAccountList) {
                        if (cardAccount.getEffectDate() != null && cardAccount.getEffectDate().getYear() != 1) {
                            if (cardAccount.getEffectDate().isBefore(LocalDate.now())) {
                                continue;
                            }
                        }
                        if (cardAccount.getAmount().compareTo(BigDecimal.ZERO) > 0) {
                            //储值账户有钱
                            if (cardAccount.getAmount().doubleValue() > Double.parseDouble(money)) {
                                //储值账户有钱并且够用
                                if ("储值账户".equals(cardAccount.getSddName())) {
                                    tradeAccountConsumptionFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_YuShouKaJi);
                                } else if ("补助账户".equals(cardAccount.getSddName())) {
                                    tradeAccountConsumptionFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_YingShouKaJi);
                                } else if ("餐票账户".equals(cardAccount.getSddName())) {
                                    tradeAccountConsumptionFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_YingShouCanPiao);
                                }
                                tradeAccountConsumptionFlow.setCustomerId(cardInfo.getCustomerId());
                                tradeAccountConsumptionFlow.setAccountId(cardAccount.getId());
                                tradeAccountConsumptionFlow.setCardId(cardInfo.getId());
                                tradeAccountConsumptionFlow.setBeforeAmount(cardAccount.getAmount());//扣前金额
                                tradeAccountConsumptionFlow.setActualAmount(Double.valueOf(money));//实扣金额
                                tradeAccountConsumptionFlow.setAfterAmount(cardAccount.getAmount().subtract(new BigDecimal(money)));//扣后金额
                                tradeAccountConsumptionFlow.setDiscountAmount(0.0);//折扣金额，待确认
                                tradeAccountConsumptionFlow.setBeforeTimes(cardAccount.getTimes());//操作前次数
                                tradeAccountConsumptionFlow.setTimes(0);
                                tradeAccountConsumptionFlow.setAfterTimes(cardAccount.getTimes());//操作后次数
                                tradeAccountConsumptionFlow.setReasonId("定额消费");
                                tradeAccountConsumptionFlow.setIsPay("0");//是否开具发票
                                tradeAccountConsumptionFlow.setCreatorId(user.getId());
                                tradeAccountConsumptionFlow.setCreatorName(user.getName());
                                tradeAccountConsumptionFlow.setCreateTime(LocalDateTime.now());
                                cardAccount.setAmount(tradeAccountConsumptionFlow.getAfterAmount());
                                cardAccountService.updateById(cardAccount);
                                tradeAccountConsumptionFlowService.save(tradeAccountConsumptionFlow);
                                flag = true;
                            } else {
                                model.addAttribute("message", "账户余额不足");
                                return JSONObject.toJSONString(model);
                            }
                        }
                    }
                }
                CardCustomerType cardCustomerType = cardCustomerTypeService.getById(autoMapper.mapperEntity(cardInfo).getCustomer().getCustomerTypeId());
                //透支情况
                if (!flag) {
                    if ("1".equals(cardCustomerType.getIsOverdraft())) {
                        //可以透支
                        for (CardAccount cardAccount : cardAccountList) {
                            if (!"按次账户".equals(cardAccount.getSddName())) {
                                if (cardAccount.getEffectDate() != null && cardAccount.getEffectDate().getYear() != 1) {
                                    if (cardAccount.getEffectDate().isBefore(LocalDate.now())) {
                                        break;
                                    }
                                }
                                if (cardAccount.getAmount().doubleValue() - Double.parseDouble(money) <= cardCustomerType.getOverdraft().doubleValue()) {
                                    if ("储值账户".equals(cardAccount.getSddName())) {
                                        tradeAccountConsumptionFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_YuShouKaJi);
                                    } else if ("补助账户".equals(cardAccount.getSddName())) {
                                        tradeAccountConsumptionFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_YingShouKaJi);
                                    } else if ("餐票账户".equals(cardAccount.getSddName())) {
                                        tradeAccountConsumptionFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_YingShouCanPiao);
                                    }
                                    tradeAccountConsumptionFlow.setCustomerId(cardInfo.getCustomerId());
                                    tradeAccountConsumptionFlow.setAccountId(cardAccount.getId());
                                    tradeAccountConsumptionFlow.setCardId(cardInfo.getId());
                                    tradeAccountConsumptionFlow.setBeforeAmount(cardAccount.getAmount());//扣前金额
                                    tradeAccountConsumptionFlow.setActualAmount(Double.valueOf(money));//实扣金额
                                    tradeAccountConsumptionFlow.setAfterAmount(cardAccount.getAmount().subtract(new BigDecimal(money)));//扣后金额
                                    tradeAccountConsumptionFlow.setDiscountAmount(0.0);//折扣金额，待确认
                                    tradeAccountConsumptionFlow.setBeforeTimes(cardAccount.getTimes());//操作前次数
                                    tradeAccountConsumptionFlow.setTimes(0);
                                    tradeAccountConsumptionFlow.setAfterTimes(cardAccount.getTimes());//操作后次数
                                    tradeAccountConsumptionFlow.setReasonId("定额消费");
                                    tradeAccountConsumptionFlow.setIsPay("0");//是否开具发票
                                    tradeAccountConsumptionFlow.setCreatorId(user.getId());
                                    tradeAccountConsumptionFlow.setCreatorName(user.getName());
                                    tradeAccountConsumptionFlow.setCreateTime(LocalDateTime.now());
                                    cardAccount.setAmount(tradeAccountConsumptionFlow.getAfterAmount());
                                    cardAccountService.updateById(cardAccount);
                                    tradeAccountConsumptionFlowService.save(tradeAccountConsumptionFlow);
                                } else {
                                    model.addAttribute("message", "交易失败,余额不足并且不可透支");
                                    return JSONObject.toJSONString(model);
                                }

                            }
                        }

                    } else {
                        model.addAttribute("message", "交易失败,余额不足并且不可透支");
                        return JSONObject.toJSONString(model);
                    }

                }
            } else if ("2".equals(configQuotaConsumption.getConfigType())) {
                //定额按次数消费
                CardAccount cardAccount = cardAccountService.findCardAccount(cardInfo.getCustomerId(), ACCOUNT_CATEGORY_ID_jici);
                if (cardAccount.getMealTimeId() != null) {
                    cardAccount = cardAccountService.findCardAccount(cardInfo.getCustomerId(), ACCOUNT_CATEGORY_ID_jici, configMealTime.getId());
                }
                if (cardAccount != null) {
                    if (cardAccount.getTimes() > 0) {
                        //有次数，可以按次消费
                        cardAccount.setTimes(cardAccount.getTimes() - configQuotaConsumption.getPrice().intValue());
                        tradeAccountConsumptionFlow.setCustomerId(cardAccount.getCustomerId());
                        tradeAccountConsumptionFlow.setAccountId(cardAccount.getId());
                        tradeAccountConsumptionFlow.setCardId(cardInfo.getId());
                        tradeAccountConsumptionFlow.setDiscountAmount(0.0);
                        tradeAccountConsumptionFlow.setBeforeTimes(cardAccount.getTimes());
                        tradeAccountConsumptionFlow.setTimes(configQuotaConsumption.getPrice().intValue());
                        tradeAccountConsumptionFlow.setAfterTimes(cardAccount.getTimes());
                        tradeAccountConsumptionFlow.setReasonId("按次消费");
                        tradeAccountConsumptionFlow.setIsPay("0");//是否开具发票
                        tradeAccountConsumptionFlow.setCardId(user.getId());
                        tradeAccountConsumptionFlow.setCreatorName(user.getName());
                        tradeAccountConsumptionFlow.setCreateTime(LocalDateTime.now());
                        tradeAccountConsumptionFlowService.save(tradeAccountConsumptionFlow);
                        cardAccountService.updateById(cardAccount);
                    } else {
                        model.addAttribute("message", "本次交易失败,没有可用的账户");
                        return JSONObject.toJSONString(model);
                    }
                }
            }
        }
        model.addAttribute("result", "success");
        model.addAttribute("message", "消费成功");
        return JSONObject.toJSONString(model);
    }


}
